package com.x.scratch.util;

import com.alibaba.fastjson.JSONObject;
import com.x.framework.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpClient {

    private static Logger logger = LoggerFactory.getLogger(HttpClient.class);

    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl    请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr     提交的数据
     */
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
        try {
            StringBuilder sb = new StringBuilder();
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod)) {
                httpUrlConn.connect();
            }

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            return sb.toString();
        } catch (ConnectException e) {
            throw new BusinessException("Weixin server connection timed out.", e);
        } catch (Exception e) {
            throw new BusinessException("https request error.", e);
        }
    }

    public static Map<String, Object> httpRequestJson(String requestUrl, String requestMethod, String outputStr) {
        String json = httpRequest(requestUrl, requestMethod, outputStr);
        Map<String, Object> map = JSONObject.parseObject(json, Map.class);
        if (map != null) {
            for (Map.Entry entry : map.entrySet()) {
                logger.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            }
        }
        return map;
    }

//    public static Map<String, Object> httpRequestXml(String xml) {
//        Map<String, Object> map = JSONObject.parseObject(xml, Map.class);
//        if (map != null) {
//            for (Map.Entry entry : map.entrySet()) {
//                logger.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//            }
//        }
//        return map;
//    }
//
//    /**
//     * 解析xml
//     */
//    public static Map doXMLParse(String strxml) throws Exception {
//        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
//
//        if (null == strxml || "".equals(strxml)) {
//            return null;
//        }
//
//        Map m = new HashMap();
//
//        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
//        SAXBuilder builder = new SAXBuilder();
//        Document doc = builder.build(in);
//        Element root = doc.getRootElement();
//        List list = root.getChildren();
//        Iterator it = list.iterator();
//        while (it.hasNext()) {
//            Element e = (Element) it.next();
//            String k = e.getName();
//            String v = "";
//            List children = e.getChildren();
//            if (children.isEmpty()) {
//                v = e.getTextNormalize();
//            } else {
//                v = getChildrenText(children);
//            }
//
//            m.put(k, v);
//        }
//        // 关闭流
//        in.close();
//        return m;
//    }
//
//    /**
//     * 获取子结点的xml
//     */
//    public static String getChildrenText(List children) {
//        StringBuffer sb = new StringBuffer();
//        if (!children.isEmpty()) {
//            Iterator it = children.iterator();
//            while (it.hasNext()) {
//                Element e = (Element) it.next();
//                String name = e.getName();
//                String value = e.getTextNormalize();
//                List list = e.getChildren();
//                sb.append("<" + name + ">");
//                if (!list.isEmpty()) {
//                    sb.append(getChildrenText(list));
//                }
//                sb.append(value);
//                sb.append("</" + name + ">");
//            }
//        }
//        return sb.toString();
//    }
}
